package com.swak.data;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import com.swak.App;
import com.swak.Constants;
import com.swak.OS;
import com.swak.lock.Lock;
import com.swak.lock.LockService;
import com.swak.registry.RegistryService;
import com.swak.registry.URL;
import com.swak.utils.Maps;

/**
 * 服务的 sn 分布式分发；
 * 
 * @author 618lf
 */
public class ServerSnDistributer implements InitializingBean {

	@Autowired(required = false)
	private RegistryService registryService;
	@Autowired(required = false)
	private LockService lockService;
	@Autowired
	private App app;
	protected URL url;

	@Override
	public void afterPropertiesSet() throws Exception {
		Map<String, String> parameters = Maps.newHashMap();
		parameters.put(Constants.Application_KEY, app.getName());
		parameters.put(Constants.Service_Key, Constants.Registry_ServerSn_Sn_Key);
		parameters.put(Constants.Server_Key, app.getId());
		this.url = new URL(Constants.Registry_ServerSn_Key, OS.ip(), 0, Constants.Registry_ServerSn_Sn_Key, parameters);
	}

	@SuppressWarnings("unused")
	public void start() {
		String path = this.url.toServicePath() + "/" + ".lock";
		Lock lock = this.lockService.newLock(path);
		lock.lock();
		try {
			
			// 查找可用的资源
			List<URL> servers = this.registryService.lookup(url);
			for (URL url : servers) {

			}
			
			// 注册已占用的资源
			if (this.registryService != null && this.url != null) {
				this.registryService.register(this.url);
			}
		} catch (Exception e) {
		} finally {
			lock.unlock();
		}
	}
}
